<!--
 * @Author: your name
 * @Date: 2020-12-22 15:20:59
 * @LastEditTime: 2021-06-16 20:33:02
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \go-admin-business\src\views\teach\components\tags.vue
-->
<template>
    <div>
        <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false" @close="handleClose(tag)">
            {{tag}}
        </el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" maxlength="4" ref="saveTagInput"
            size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 标签</el-button>
    </div>
</template>
<script>

export default {
    data () {
        return {
            dynamicTags: [],
            inputVisible: false,
            inputValue: ''
        };
    },
    props: ['val'],
    mounted () {
        console.log(this.val)
        if (this.val) {
            this.dynamicTags = this.val.split(',')
        } else {
            this.dynamicTags = [];
        }
    },
    watch: {
        val () {
            if (this.val) {
                this.dynamicTags = this.val.split(',')
            } else {
                this.dynamicTags = [];
            }
        },
    },
    methods: {
        handleClose (tag) {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
            this.$emit('update:val', this.dynamicTags.join(','))
        },

        showInput () {
            // if (this.dynamicTags.length >= 2) {
            //     this.$message.error('您最多只能添加2个标签')
            //     return false
            // }
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },

        handleInputConfirm () {
            let inputValue = this.inputValue;
            if (inputValue) {
                this.dynamicTags.push(inputValue);
                this.$emit('update:val', this.dynamicTags.join(','))

            }
            this.inputVisible = false;
            this.inputValue = '';
        }
    }
}
</script>
<style lang="scss" scoped>
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>
